package org.news.web.utils;

import cn.hutool.core.util.ObjectUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.redis.utils.RedisUtils;
import org.news.web.redis.RedisConstant;

import java.time.Duration;

public class UserInfoInterceptorUtils {


    public static Boolean CheckUserInfoKey(HttpServletRequest request){
        String authorization = request.getHeader("Authorization");
        System.out.println( "用户key：" +authorization);
        if(StringUtils.isBlank(authorization)){
            // 用户登录信息失效请重试
//            throw new ServiceException("请登录后访问！");
            return false;
        }
//        校验key是否合规
        Object userIdStr = RedisUtils.getCacheObject(RedisConstant.USER_KEY + ":" + authorization);
        if(ObjectUtil.isNull(userIdStr)){
            return false;
        }


//        更新缓存过期时间
        RedisUtils.expire(RedisConstant.USER_KEY + ":" + authorization,Duration.ofMinutes(30l));
        return true;
    }

    public static Long getUserId(HttpServletRequest request){
        String authorization = request.getHeader("Authorization");
        Object userIdStr = RedisUtils.getCacheObject(RedisConstant.USER_KEY + ":" + authorization);
        return Long.valueOf(String.valueOf(userIdStr));
    }
}
